# -*- coding: utf-8 -*-
from PyQt4.QtCore import SIGNAL, QTimer, Qt, QRect
from PyQt4.QtGui import QGraphicsLinearLayout, QColor
from PyKDE4.plasma import Plasma
from PyKDE4 import plasmascript
from commands import getoutput
from os import listdir

class NetbookLED(plasmascript.Applet):
    def __init__(self, parent, args=None):
        plasmascript.Applet.__init__(self, parent)
        self.__ledvalues = dict()

    def init(self):
        self.setHasConfigurationInterface(False)

        self.setAspectRatioMode(Plasma.Square)
        # Is any of this really needed?
        self.theme = Plasma.Svg(self)
        self.theme.setImagePath("widgets/background")
        self.setBackgroundHints(Plasma.Applet.DefaultBackground)

        # still not sure how this changes anything
        self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet)

        self.applet.setLayout(self.layout)
        self.resize(66, 22)

        self.timer = QTimer()
        self.connect(self.timer, SIGNAL("timeout()"), self.check_update)
        self.timer.start(250)

    def check_update(self):
        if self.ledvalues != self.__ledvalues:
            self.__ledvalues = self.ledvalues
            self.update()

    def paintInterface(self, painter, option, rect):
        painter.save()
        caps_rect = QRect(0,0, (rect.width()/3)-1, rect.height())
        num_rect = QRect((rect.width()/3)+1, 0, (rect.width()/3)-1, rect.height())
        cam_rect = QRect(((rect.width()/3)*2)+1, 0, (rect.width()/3)-1, rect.height())
        ledvalues = self.ledvalues
        painter.fillRect(caps_rect, QColor(0, 0, self.ledstatus(ledvalues['capslock']), 128))
        painter.fillRect(num_rect, QColor(0, 0, self.ledstatus(ledvalues['numlock']), 128))
        painter.fillRect(cam_rect, QColor(0, 0, self.ledstatus(ledvalues['camera']), 128))
        painter.restore()

    def ledstatus(self, boolean):
        if boolean:
            return 255
        else:
            return 0

    @property
    def ledvalues(self):
        output = getoutput('xset q | grep "LED mask"')
        ledmask = bin(int(output[-1], 16))[-2:]
        capslock = bool
        if (ledmask[0] == 'b') or (ledmask[0] == '0'):
            numlock = False
        elif ledmask[0] == '1':
            numlock = True
        if ledmask[1] == '0':
            capslock = False
        elif ledmask[1] == '1':
            capslock = True
        if 'video0' in listdir('/dev/'):
            camera = True
        else:
            camera = False
        return {'capslock': capslock, 'numlock': numlock, 'camera': camera}


def CreateApplet(parent):
    return NetbookLED(parent)